<template>
  <div class="tradeHis-root">
		
    <van-nav-bar
      right-text="交易记录"
      left-arrow
      @click-left="$router.goBack()"
      @click-right="detail.id>0?$router.push('/transactionHis?rule_id=' + detail.id):''"
    />

    <div class="bg">
      <div class="name-box flex">
        <div class="name">{{ detail.name }}</div>
        <div class="label" v-if="detail.type == 1">策略循环</div>
        <div class="label" v-if="detail.type == 2">单次策略</div>
      </div>

      <div class="tab-box">
        <div class="row">
          <div class="col">
            <div class="title">持仓金额（USDT)</div>
            <div class="num">{{ detail.amount }}</div>
          </div>

          <div class="col" style="margin-left: 0.5rem">
            <div class="title">持仓均价</div>
            <div class="num">{{ detail.unit_price }}</div>
          </div>

          <div class="col">
            <div class="title">补仓次数</div>
            <div class="num">{{ detail.cover_times }}</div>
          </div>
        </div>

        <div class="row">
          <div class="col">
            <div class="title">持仓数量（{{ detail.name }})</div>
            <div class="num">{{ detail.quantity }}</div>
          </div>

          <div class="col" style="margin-left: 0.5rem">
            <div class="title">当前价格</div>
            <div class="num">{{ detail.current_price }}</div>
          </div>

          <div class="col">
            <div class="title">涨幅</div>
            <div class="num">{{ detail.profit }} %</div>
          </div>
        </div>
      </div>
    </div>

    <div class="info-box">
      <div class="title-box flex">
        <div class="line"></div>
        <div class="title">策略相关</div>
      </div>

      <div class="tab-box">
        <div class="flex row">
          <div class="flex col">
            <div class="title">首单额度</div>
            <div class="num">{{ detail.first_amount }}</div>
          </div>

          <div class="flex col">
            <div class="title">倍投上限</div>
            <div class="num">{{ detail.num }}</div>
          </div>
        </div>

        <div class="flex row">
          <div class="flex col">
            <div class="title">止盈比例</div>
            <div class="num">{{ detail.stop_profit_ratio }} %</div>
          </div>

          <div class="flex col">
            <div class="title">盈利回调</div>
            <div class="num">{{ detail.stop_profit_callback }} %</div>
          </div>
        </div>

        <div class="flex row">
          <div class="flex col">
            <div class="title">补仓跌幅</div>
            <div class="num">{{ detail.overlap }} %</div>
          </div>

          <div class="flex col">
            <div class="title">补仓回调</div>
            <div class="num">{{ detail.cover_callback }} %</div>
          </div>
        </div>

        <div class="flex row">
          <div class="flex col">
            <div class="title">补仓价格</div>
            <div class="num">--</div>
          </div>

          <div class="flex col">
            <div class="title"></div>
            <div class="num"></div>
          </div>
        </div>
      </div>

      <div class="title-box flex">
        <div class="line"></div>
        <div class="title">策略操作</div>
      </div>

      <div class="btn-box flex-btw">
        <div v-if="detail.type == 2" class="col">
          <img
            src="@/assets/images/tradeHis/2.png"
            alt=""
            @click="setType(1)"
          />
          <div class="text">策略循环</div>
        </div>

        <div v-if="detail.type <= 1" class="col">
          <img
            src="@/assets/images/tradeHis/5.png"
            alt=""
            @click="setType(2)"
          />
          <div class="text">单次策略</div>
        </div>

        <div class="col">
          <img src="@/assets/images/tradeHis/3.png" alt="" @click="dealOrder(2)"/>
          <div class="text">清仓卖出</div>
        </div>

        <div class="col">
          <img src="@/assets/images/tradeHis/4.png" alt="" @click="show = !show" />
          <div class="text">一键补仓</div>
        </div>
      </div>

      <div class="setting-box flex-center">
        <div
          class="btn"
          @click="$router.push({ name: 'Setting', params: { ids: id } })"
        >
          交易设置
        </div>
        <div class="btn" v-if="detail.is_open == 2" @click="setOpen(1)">
          启动
        </div>
        <div class="btn" v-if="detail.is_open == 1" @click="setOpen(2)">
          关闭
        </div>
      </div>
    </div>

    <!-- 弹框 -->
    <van-dialog v-model="show" title="买入USDT" show-cancel-button :before-close="beforeClose">
      <div class="flex">
        <van-field
          v-model="amount"
          clearable
          label="数量："
          label-width="1rem"
          placeholder="请输入买入数量"
        />
        <div style="margin-right: .3rem">USDT</div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import mixin from "@/mixin.js";
import { TRADE_DETAIL, RULE_SET,DEAL_ORDER } from "@/api/api.js";
import { Toast } from "vant";
export default {
  name: "register",
  mixins: [mixin],
  data() {
    return {
      timerId:'',
      id: "",
      name: "",
      detail: [],
      typeParam: {},
      show: false,
      amount: 0,
			overlap:0,
			websock: null,
    };
  },
  watch: {
    "$route.query.id"(n) {
      if (typeof(n) != 'undefined') {
        this.timerGetDetails(n);
      } else {
        this.timerId = '';
      }
    },
  },
	created() {
		//this.initWebSocket();
	},
	destroyed() {
		//this.websock.close() //离开路由之后断开websocket连接
	},
  mounted() {
    let id = this.$route.query.id;
		console.log(id)
    this.id = id;

    this.timerGetDetails(id);

  },
  methods: {
      timerGetDetails(id) {
        this.timerId = Math.random();
        this.getDetail(id,this.timerId);
      },

      timer(id,timerId) {
        if(this.timerId != timerId) {
          return '';
        }
        return setTimeout(() => {
          this.getDetail(id,timerId);
        }, 1000);
      },
		initWebSocket(){ 
			//初始化weosocket
			const wsuri = "wss://api-aws.huobi.pro/ws";
			this.websock = new WebSocket(wsuri);
			this.websock.onmessage = this.websocketonmessage;
			this.websock.onopen = this.websocketonopen;
			this.websock.onerror = this.websocketonerror;
			this.websock.onclose = this.websocketclose;
		},
		websocketonopen(){ 
			//连接建立之后执行send方法发送数据
			let actions = {"sub":"market.btcusdt.trade.detail","id":"BTC"};
			//let actions = {"sub": "market.ethbtc.kline.1min","id": "id1"};
			this.websocketsend(JSON.stringify(actions));
		},
		websocketonerror(){
			//连接建立失败重连
			this.initWebSocket();
		},
		websocketonmessage(e){ 
			//数据接收
			const redata = JSON.parse(e.data);
			console.log(redata);
		},
		websocketsend(Data){
			//数据发送
			this.websock.send(Data);
		},
		websocketclose(e){  
			//关闭
			console.log('断开连接',e);
		},
		beforeClose : function (action, done) { // 点击事件 - 备注按钮提示框
		  if (action === 'confirm') { // 确认
		   console.log('[点击事件 - 备注] - 确认');
              this.dealOrder(1)
			 done(); // 关闭提示框
		  } else if(action === 'cancel') {
				done(); // 关闭提示框
			}
		},
    async getDetail(id,timerId) {
      try{
        const { data } = await this.$reqGet(TRADE_DETAIL + "?id=" + id, {});
        if (data.status == 1) {
          this.detail = data.data;
                  this.id = id;
          this.detail.profit = (100 * this.detail.profit).toFixed(3);
                  if(!this.detail.id && this.detail.overlap_arr.length>0) {
                      this.overlap = this.detail.overlap_arr[this.cover_times+1].callback;
                  }
        }
      }catch (e) {
      }
      if(typeof(timerId) != 'undefined' && timerId) {
        this.timer(id,timerId);
      }
    },
    async setType(type) {
      this.typeParam = {};
			if(!this.detail.id) {
				Toast('请先进行交易设置');
				return false;
			}
      this.typeParam.type = type;
      this.typeParam.coin_id = this.id;
      const { data } = await this.$reqPost(RULE_SET, this.typeParam);
      if (data.status == 1) {
        Toast(data.info);
        this.detail.type = type;
      }
    },
    async setOpen(is_open) {
      this.typeParam = {};
			if(!this.detail.id) {
				Toast('请先进行交易设置');
				return false;
			}
      this.typeParam.is_open = is_open;
      this.typeParam.coin_id = this.id;
      const { data } = await this.$reqPost(RULE_SET, this.typeParam);
      if (data.status == 1) {
        Toast(data.info);
        this.detail.is_open = is_open;
      }
    },
		async dealOrder(type) {
          this.typeParam = {};
			if(!this.detail.id) {
				Toast('请先进行交易设置');
				return false;
			}
			if(!this.detail.coin_rule_run_id && type==2) {
				Toast('持仓数量为0');
				return false;
			}
			if(this.detail.is_open==1 && type==2) {
				Toast('请先关闭交易对再清仓');
				return false;
			}
		  this.typeParam.type = type;
		  this.typeParam.coin_rule_id = this.detail.id;
			this.typeParam.coin_rule_run_id = this.detail.coin_rule_run_id;
			this.typeParam.price = this.detail.current_price;
			this.typeParam.unit_price = this.detail.unit_price;
			this.typeParam.version = this.detail.version;
			if(type ==2) {
				this.typeParam.amount = this.detail.amount;
			} else {
				this.typeParam.amount = this.amount;
			}
		  const { data } = await this.$reqPost(DEAL_ORDER, this.typeParam);

		  if (data.status === 1) {
				this.getDetail(this.id);
				if(type ==2) {
					Toast('操作成功');
				} else {
					return true;
				}
		  } else {
              Toast(data.info);
				return false;
			}
		},
  },
};
</script>

<style lang="scss" scoped>
.tradeHis-root {
  position: relative;

  .bg {
    position: absolute;
    top: 0;
    background: url("../../assets/images/tradeHis/1.png");
    width: 100%;
    height: 4.58rem;
    background-position: -0.05rem -0.05rem;
    background-size: 102% 102%;
    padding-top: 1.05rem;

    .name-box {
      padding: 0 0.3rem;
      margin-bottom: 0.18rem;
      .name {
        font-size: 0.48rem;
        color: #fff;
      }
      .label {
        margin-left: 0.3rem;
        width: 1.16rem;
        height: 0.36rem;
        color: #fff;
        font-size: 0.24rem;
        line-height: 0.36rem;
        background-color: #f8b551;
      }
    }

    .tab-box {
      padding: 0 0.3rem;

      .row {
        display: flex;
        justify-content: center;
        &:nth-child(1) {
          margin-bottom: 0.5rem;
        }

        .col {
          flex: 1;
          .title {
            text-align: left;
            font-size: 0.24rem;
            color: #dcdbdb;
            margin-bottom: 0.16rem;
          }

          .num {
            text-align: left;
            font-size: 0.34rem;
            color: #fefefe;
          }
        }
      }
    }
  }

  .info-box {
    position: relative;
    top: calc(4.58rem - 46px);
    padding-top: 0.45rem;

    .title-box {
      margin-bottom: 0.42rem;
      padding: 0 0.3rem;
      .line {
        width: 0.08rem;
        height: 0.3rem;
        background-color: #2d7afe;
      }

      .title {
        font-size: 0.34rem;
        margin-left: 0.3rem;
      }
    }

    .tab-box {
      border-bottom: 0.1rem solid #efefef;
      padding: 0 0.3rem 0.6rem;
      margin-bottom: 0.46rem;

      .row {
        margin-bottom: 0.23rem;
        &:last-child {
          margin-bottom: 0;
        }
        .col {
          flex: 1;
          font-size: 0.26rem;

          .title {
            margin-right: 0.26rem;
            margin-left: 0.38rem;
            color: #a5a5a5;
          }

          .num {
            color: #2d7afe;
          }
        }
      }
    }

    .btn-box {
      padding: 0 0.6rem;
      .col {
        img {
          width: 1.47rem;
          height: 1.47rem;
        }

        .text {
          text-align: center;
          font-size: 0.26rem;
          margin-top: -0.2rem;
          color: #141414;
        }
      }
    }

    .setting-box {
      margin-top: 0.52rem;
      .btn {
        width: 1.6rem;
        height: 0.57rem;
        font-size: 0.26rem;
        background-color: #2d7afe;
        line-height: 0.57rem;
        color: #fff;
        border-radius: 0.1rem;
        margin: 0 0.26rem;
      }
    }
  }
}
</style>
